import json

import requests
from django import http

from django.contrib import messages
from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import HttpResponse
from django.shortcuts import render, redirect,reverse
from django.contrib.auth import login, logout, authenticate
from django.contrib import messages
from django.views import View
from django.core.cache import cache
from geetest import GeetestLib
from pymysql import DatabaseError

from apps.SongList.models import Song
from apps.payment.models import OrderInfo
from apps.singers.models import follow_artist
from apps.users.models import User, PlayList_Follow, Album_Follow
from utils.push_image import storage

pc_geetest_id = '239d43a905bd9289175183296255b2bd'
pc_geetest_key = '23b7d0abf8398637bba28d7d015d6bde'


class Login_View(View):
    """登录"""
    def get(self, request):
        return render(request, 'login.html')
    def post(self, request):
        mobile = request.POST.get('username')
        password = request.POST.get('password')

        # 判断用户信息
        if not all([mobile, password]):
            messages.success(request, "缺少参数")
            return render(request, 'login.html')

        # 查询数据是否正确

        user = authenticate(username=mobile, password=password)
        if user is None:
            messages.success(request, "用户名或密码错误")
            return render(request, 'login.html')

        # 状态保持
        a = User.objects.filter(username=mobile)
        for x in a:
            print('--------------------------2-------------------------')
            request.session['user_id'] = x.id

        login(request, user)

        request.session['username'] = mobile
        next = request.GET.get('next')
        if next:
            response = redirect(next)
        else:
            # 返回主页面
            response = redirect(reverse('index:main'))
        response.set_cookie('username', user.username, max_age=3600 * 24 * 15)
        return response


class RegisterView(View):
    """注册"""
    def get(self, request):
        return render(request, "register.html")
    def post(self, request):
        #  获取数据
        username = request.POST.get('username')
        password = request.POST.get('password')
        confirm_password = request.POST.get('confirm_password')
        phone_number = request.POST.get('phone_number')
        print(username, confirm_password, password,phone_number)

        if not all([username, password, confirm_password, phone_number]):
            messages.success(request, "请补充数据")
            return render(request, 'register.html')
        # 赋值字段
        try:
            user = User.objects.create_user(username=username, password=password, mobile=phone_number)
        except DatabaseError:
            messages.success(request, "注册失败")
            return render(request, 'register.html')
        login(request, user)
        request.session['username'] = username
        request.session['user_id'] = user.id
        response = redirect(reverse('index:main'))
        response.set_cookie('username', user.username, max_age=3600 * 24 * 15)
        return response


class LogoutView(View):
    """退出登录"""
    def get(self, request):
        logout(request)
        user_id = request.session.get('user_id')
        if user_id:
            del request.session['user_id']
        response = redirect(reverse('index:main'))
        response.delete_cookie('username')

        return response


class User_Center_View(LoginRequiredMixin, View):
    """个人中心"""
    def get(self, request):

        user_pic = request.session.get('user_pic')
        user_id = request.session.get('user_id')

        username = request.session.get('username')
        request.session['user_pic'] = user_pic
        request.session['username'] = username
        my_list = PlayList_Follow.objects.filter(users_id=user_id)
        users = User.objects.filter(id=user_id)
        is_vip = OrderInfo.objects.filter(user_id=user_id)
        user_img = ''
        for x in users:
            user_img = x.user_img
        content = {
            'user_pic': user_img,
            'user_id': user_id,
            'user_like_list': '',
            'i_like': '',
            'username': username,
            'my_list': my_list,
            'is_vip': is_vip
        }
        return render(request, 'my_center.html', content)

    def post(self, request):
        # 获取数据
        list_name = request.POST.get('list_name')
        user_id = request.session.get('user_id')
        user_pic = request.session.get("user_pic")
        user_like_list = request.session.get("user_like_list")
        users_like_list = request.session.get("users_like_list")
        username = request.session.get("username")
        print(user_id)

        content = {
            'user_pic': user_pic,
            'user_id': user_id,
            'user_like_list': user_like_list,
            'i_like': users_like_list,
            'username': username,
        }

        # 判断数据
        if not list_name:
            messages.success(request, "您输入的账号或密码有误请重新输入")
            # return render(request, 'my_center.html', content)
            return redirect(reverse('users:center'), content)
        try:

            a = PlayList_Follow.objects.create(playlist_name=list_name, users_id=user_id)
            a.save()
            return redirect(reverse('users:center'), content)

        except Exception as e:
            print('=================',e)
            messages.success(request, "添加失败")
            return redirect(reverse('users:center'), content)


class User_Follow_View(LoginRequiredMixin, View):
    def get(self, request):
        user_pic = request.session.get('user_pic')
        user_id = request.session.get('user_id')
        users = User.objects.filter(id=user_id)
        is_vip = OrderInfo.objects.filter(user_id=user_id)
        user_img = ''
        for x in users:
            user_img = x.user_img
        user_follow = follow_artist.objects.filter(user_id=user_id)


        content = {
            'user_id': user_id,
            'user_pic': user_img,
            'user_follow': user_follow,
            'is_vip': is_vip
        }
        return render(request, "my_follow.html",content)


class Del_Follow_List(LoginRequiredMixin, View):
    def get(self, request):
        # 将数据进行数据库对比
        ids = request.GET.get('id')
        list_id = PlayList_Follow.objects.get(id=ids)
        # if not (list_id and request.user == list_id.user):
        #     return http.HttpResponseBadRequest("非法操作")
        # 将选中的id删除
        try:
            list_id.is_deleted = True
            list_id.save()
        except Exception as e:
            print(e, '=================================')
            messages.success(request, "删除失败")
            return redirect(reverse('users:center'))
        messages.success(request, "删除成功")
        return redirect(reverse('users:center'))


class User_Like_View(LoginRequiredMixin, View):
    """用户喜欢的音乐"""
    def get(self, request):

        user_id = request.session.get('user_id')
        print(user_id)
        user_like = Song.objects.filter(user_id=user_id)
        song_list = PlayList_Follow.objects.filter(users_id=user_id)
        album_list = Album_Follow.objects.filter(users_id=user_id)
        users = User.objects.filter(id=user_id)
        is_vip = OrderInfo.objects.filter(user_id=user_id)
        user_img = ''
        for x in users:
            user_img = x.user_img
        song_list_count = 0
        for x in song_list:
            if x.playlist_id:
                song_list_count += 1

        song_count = 0
        for x in user_like:
            if x.song_id and x.is_song == 1:
                song_count += 1

        album_count = 0
        for x in album_list:
            if x.album_id:
                album_count += 1

        content = {
            'user_pic': user_img,
            'user_id': user_id,
            'user_like': user_like,
            'song_list': song_list,
            'album_list':album_list,
            'song_list_count': song_list_count,
            'song_count': song_count,
            'album_count': album_count,
            'is_vip': is_vip,

        }
        return render(request, 'my_like.html', content)




def pcgetcaptcha(request):
    user_id = 'test'
    gt = GeetestLib(pc_geetest_id, pc_geetest_key)
    status = gt.pre_process(user_id)
    request.session[gt.GT_STATUS_SESSION_KEY] = status
    request.session["user_id"] = user_id
    response_str = gt.get_response_str()
    return HttpResponse(response_str)


